const Koa = require('koa')
const Router  = require('koa-router')
const staticServer = require('koa-static');


const child_process = require('child_process') 
const path = require('path')

// 创建一个Koa对象表示web app本身:
const app = new Koa();
const router = new Router();
app.use(staticServer(__dirname , 'public'));


// 对于任何请求，app将调用该异步函数处理请求：
app.use(async (ctx, next) => {
  console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
  await next();
});

const execPromise = (...arg) =>
        new Promise((r, j) => {
            child_process.exec(...arg, (err, stdout) => {
                if (err) {
                    j(err);
                } else {
                    r(stdout);
                }
            });
        });

const VIDEO_ROOT_DIR = "D://video/"

router.get('/videos/:videoFile', async (ctx)=>{
    const {
        params: { videoFile },
      } = ctx;
    const videoFilePath = path.join(VIDEO_ROOT_DIR, videoFile);
    // 调用 ffprobe 分析视频 I 帧分布
    // const cmdReadKeyframe = `ffprobe -v error -skip_frame nokey -select_streams v:0 -show_entries frame=pkt_pts_time -of csv=print_section=0 ${videoFilePath}`;
    // console.log(cmdReadKeyframe)
    // const keyframes = (await execPromise(cmdReadKeyframe))
    // .split('\n')
    // .filter((d) => d > 0)
    // .map((d) => parseInt(d));
    // keyframes.splice(0,0,0)
    
    // 调用 ffprobe 解析视频原信息
  const cmdReadMeta = `ffprobe -v quiet -print_format json -show_format -show_streams ${videoFilePath}`;
  const result = JSON.parse(await execPromise(cmdReadMeta));
  let {
    format: { duration }
  } = result;
  console.log(duration)
  // 根据关键帧的时间分布和视频时长，生成 m3u8 文件
//   const fragments = keyframes.map((k, i) => ({
//     duration: i === keyframes.length - 1 ? duration - k : keyframes[i + 1] - k,
//     start: k
//   }));

  const fragments = []
  let start = 0
  let len = 10
  while(duration > 0){
      fragments.push({start: start, duration: len})
      start += len
      duration -= len
  }
    ctx.body =
    	'#EXTM3U\n' +
      '#EXT-X-PLAYLIST-TYPE:VOD\n' +
      `#EXT-X-TARGETDURATION:${Math.max(...fragments.map((f) => f.duration))}\n` +
    	`${fragments
        .map(
          (f) =>
            `#EXTINF:${f.duration},\n/hls_video/${videoFile}?start=${f.start}&duration=${f.duration}`
        )
        .join('\n')}\n` +
  			'#EXT-X-ENDLIST';
    ctx.type = 'application/x-mpegURL';

})

router.get('/hls_video/:videoFile',async (ctx)=>{
    const {
        params: { videoFile },
        query: {start, duration }
      } = ctx;
      const videoFilePath = path.join(VIDEO_ROOT_DIR, videoFile);
      // ffmpeg 截取视频片段
      const cmd = `-ss ${start} -i ${videoFilePath} -t ${duration} -vcodec copy -acodec copy -b:v 200k -f hls -c:a aac -c:v libx264 -output_ts_offset ${start} -`;
      // spawn使用指定的命令行参数创建新进程
      // spawn会返回一个带有stdout和stderr流的对象
      // 你可以通过stdout流来读取子进程返回给Node.js的数据
      const { stdout } = child_process.spawn('ffmpeg', cmd.split(' '));
    
      ctx.type = 'video/MP2T';
      ctx.body = stdout;
    
})
app.use(router.routes());
app.listen(91);
console.log('app started at port 91...');